package com.ss.project.xia17user.config.security.form;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 表单认证成功处理器
 * 认证成功后先跳转至上个页面，如果没有那么跳转至首页
 * @author xia17
 * @date 2020/10/14 16:01
 */
@Slf4j
public class FormAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private final RequestCache requestCache = new HttpSessionRequestCache();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        // 获取缓存
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        if (savedRequest == null) {
            // 如果没有缓存默认跳转至Index
            String defaultTargetUri = "http://" + request.getServerName() + ":" + request.getServerPort();
            sendJson(response,defaultTargetUri);
            return;
        }
        // Use the DefaultSavedRequest URL
        String targetUrl = savedRequest.getRedirectUrl();
        log.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
        sendJson(response,targetUrl);
    }

    /**
     * 返回JSON
     * @param response /
     * @param targetUrl /
     * @throws IOException /
     */
    private void sendJson(HttpServletResponse response , String targetUrl) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        String sb = "{\"code\":1,\"uri\":\"" +
                targetUrl +
                "\"}";
        out.write(sb);
        out.flush();
        out.close();
    }


}
